import { createRouter, createWebHistory } from 'vue-router'
import { type RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from '@/stores/index'
import { userInfos } from '@/stores/user'
import { gloabl } from '@/stores/global'
import { Local } from '@/utils/storage'
import { NextLoading } from '@/utils/loading'
import { editorInfos } from '@/stores/editor'
import { message } from 'ant-design-vue'

const userInfoStore = userInfos(pinia)
const globalStore = gloabl(pinia)

// 扩展 RouteMeta 接口
declare module 'vue-router' {
  interface RouteMeta {
    title?: string
    isLink?: string
    disabledLoading?: boolean //设置全局的Loading与否
    requiredLogin?: boolean
    redirectAlreadyLogin?: boolean
  }
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/home',
    meta: {
      isKeepAlive: true
    },
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          title: 'message.router.home',
          isLink: '',
          isHide: false,
          isKeepAlive: true
        }
      },
      {
        path: '/template/:id',
        name: 'template',
        component: () => import('@/views/templates/index.vue'),
        meta: {
          title: 'message.router.template',
          isLink: '',
          isHide: false,
          isKeepAlive: true,
          isAffix: true,
          isIframe: false
        }
      },
      {
        path: '/mywork',
        name: 'MyWork',
        component: () => import('@/views/my-works/index.vue'),
        meta: { requiredLogin: true, title: '我的设计列表' }
      },
    ]
  },
  {
    path: '/work/editor/:id',
    name: 'workEditor',
    component: () => import('@/views/editor/index.vue'),
    meta: {
      title: 'message.router.editor',
      isLink: '',
      isHide: false,
      isKeepAlive: true,
      isAffix: true,
      isIframe: false,
      requiredLogin: true
    }
  },
  {
    path: '/threeEarth',
    name: 'threeEarth',
    component: () => import('@/views/threeD/index.vue'),
    meta: {
      title: 'threeEarth',
      isLink: '',
      isHide: false,
      isKeepAlive: true,
      isAffix: true,
      isIframe: false,
      requiredLogin: false
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: 'message.router.login',
      isLink: '',
      isHide: false,
      isKeepAlive: true,
      redirectAlreadyLogin: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...routes]
})

// 路由加载前
router.beforeEach(async (to, from) => {
  const { token, isLogin } = userInfoStore
  const { title, requiredLogin, redirectAlreadyLogin } = to.meta
  NProgress.configure({ showSpinner: false })
  if (title) {
    document.title = title
    NProgress.start()
  }
  if (!isLogin) {
    if (token) {
      try {
        await userInfoStore.setUserInfos()
        if (!userInfoStore.isLogin) {
          NProgress.done()
          userInfoStore.logout()
          return '/login'
        }
        if (redirectAlreadyLogin) {
          NProgress.done()
          return '/'
        }
      } catch (error) {
        message.error('登陆状态已过期 请重新登录', 2)
        userInfoStore.logout()
        NProgress.done()
        return '/login'
      }
    } else {
      if (requiredLogin) {
        NProgress.done()
        return '/login'
      }
    }
  } else {
    if (redirectAlreadyLogin) {
      NProgress.done()
      return '/'
    }
  }

  // if (to.path === '/login' && !token) {
  //   next()
  //   NProgress.done()
  // } else {
  //   if (!token) {
  //     next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`)
  //     Local.clear()
  //     NProgress.done()
  //   } else if (token && to.path === '/login') {
  //     next('/home')
  //     NProgress.done()
  //   } else {
  //     // 界面 loading 动画开始执行
  //     if (window.nextLoading === undefined) NextLoading.start()
  //     // 无 token 停止执行下一步
  //     if (!token) return false
  //     await userInfoStore.setUserInfos()
  //     next()
  //   }
  // }
})
// 路由加载后
router.afterEach(() => {
  NProgress.done()
})
export default router
